package com.xianggu.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NioClient {
    private static final String HOST = "localhost";
    private static final int PORT = 8080;
    
    public static void main(String[] args) throws IOException {
        SocketChannel client = SocketChannel.open();
        client.configureBlocking(false);
        client.connect(new InetSocketAddress(HOST, PORT));

        // 等待连接完成
        while (!client.finishConnect()) {
            System.out.println("Establishing connection...");
        }

        System.out.println("Connected to server");
        new Thread(() -> handleRead(client)).start();
        
        // 发送消息
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String input = scanner.nextLine();
            sendMessage(client, input);
        }
    }

    private static void sendMessage(SocketChannel client, String msg) {
        try {
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            client.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleRead(SocketChannel client) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            while (client.read(buffer) > 0) {
                buffer.flip();
                byte[] data = new byte[buffer.remaining()];
                buffer.get(data);
                System.out.println("Server response: " + new String(data));
                buffer.clear();
            }
        } catch (IOException e) {
            System.out.println("Connection closed");
        }
    }
}